package com.forum.Controller;

import com.common.Entity.Result;
import com.common.Utils.JwtUtil;
import com.forum.Entity.Comment;
import com.forum.Entity.Like;
import com.forum.Service.CommentService;
import com.forum.Service.LikeService;
import com.forum.Service.PostService;
import com.forum.Service.SysService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@RestController
@RequestMapping("/like")
public class LikeController {
    @Autowired
    private LikeService likeService;
    @Autowired
    private SysService sysService;
    @Autowired
    private PostService postService;
    @Autowired
    private CommentService commentService;

    //获取当前用户点赞列表记录
    @GetMapping("/getLikesList")
    public Result getLikesList(@RequestParam String token) {
        String username = JwtUtil.extractUsername(token);

        //远程调用
        String userId =sysService.getUserByName(username);
        List<Like> likeList = likeService.getLikesList(userId);
        return Result.success(likeList);
    }
    @PostMapping("/like")
    public Result addLike(@RequestBody Like like) {
        String token=like.getToken();
        String username = JwtUtil.extractUsername(token);
        like.setUserId(sysService.getUserByName(username));
        like.setCreateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        likeService.addLike(like);
        if (like.getTargetType().equals("POST")){
            postService.addLikes(like.getTargetId());
        }else if (like.getTargetType().equals("COMMENT")){
            commentService.addlikes(like.getTargetId());
        }else if (like.getTargetType().equals("REPLY")) {
            commentService.addlikes(like.getTargetId());
        }
        return Result.success();
    }

    @PostMapping("/unlike")
    public Result unLike(@RequestBody Like like) {
        String token=like.getToken();
        String username = JwtUtil.extractUsername(token);
        String userId =sysService.getUserByName(username);
        String targetId = like.getTargetId();
        likeService.deleteLike(userId, targetId);
        switch (like.getTargetType()) {
            case "POST":
                postService.cutLikes(like.getTargetId());
                break;
            case "COMMENT":
                commentService.cutlikes(like.getTargetId());
                break;
            case "REPLY":
                commentService.cutlikes(like.getTargetId());
                break;
        }
        return Result.success();
    }
}
